package cn.player.media.view;

import android.content.Context;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import cn.player.R;
import cntv.player.core.util.AnimController;
import cntv.player.core.util.LogUtil;
import cntv.player.core.util.StringUtil;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.widget.BaseMediaController;

public class CustomerMediaController extends BaseMediaController {
    private static final String TAG = "zl";
    private static final int mDefaultTimeout = 5000;
    private static final int FADE_OUT_CONTROLLER = 1;
    private static final int SHOW_PLAY_PROGRESS = 2;
    private static final int SHOW_BUFFER_PROGRESS = 3;
    private static final int FADE_OUT_VOLUME = 4;
    private static final int REMOVE_CONTROLLER = 6;

    private Context mContext;

    private View mRoot;
    private ViewGroup mAnchor;
    private View mGestureView;
    private View mVolumeView;
    private SeekBar mScheduleProgress;// 进度条
    private TextView mEndTime, mCurrentTime;
    private TextView mFileName;

    private ImageButton mPauseButton;
    private RelativeLayout mRlTop;
    private LinearLayout mLlBottom;
    private LinearLayout mLlLeft;
    private LinearLayout mLlRight;
    private LinearLayout mLlPlayMode;
    private LinearLayout mLlVerticalVolume;
    private LinearLayout mLlTimeShiftAdjust;

    private RelativeLayout mRlRootGesture;
    private ImageView ivGestureDirection;
    private TextView tvGestureCur;
    private TextView tvGestureTotal;
    private VerticalSeekBar mVsbVolume;

    private String mTitle = "i am not been set!";
    public boolean mShowing;
    public boolean mIsAnimShowing;
    public boolean mIsAnimHiding;

    private int mCurrentBufferPercentage;
    private boolean isLiveFlag;
    private boolean isAdPlaying;

    private long mDuration;
    protected long newPosition;
    protected long nowPosition;
    protected long bufferTime;
    protected int newPercent;
    protected String newTime;
    private int mProgress;
    //	protected boolean mIsVideoPlay;
//	protected boolean mIsFirstPlay = true;
    private boolean isPaused;//用来处理播放暂停按钮更新不及时的问题，mPlayer.isPlaying()方法返回值更新不及时导致
    private boolean isVideoPaused;//视频暂停状态下被覆盖时， 恢复时仍然为暂停状态
    private OnClickListener mPauseListener;

    private OnShownListener mShownListener;
    private OnClickPauseListener mOnClickPauseListener;
    private OnHiddenListener mHiddenListener;

    private OnSeekBarChangeListener mSeekListener;

    private AudioManager mAudioManager;
    private int mMaxVolume;
    private int mCurrentVolume;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FADE_OUT_VOLUME:
                    AnimController.getInstance().fadeOut(mLlVerticalVolume, 350, 0);//全屏音量窗口隐藏
                    break;
                case FADE_OUT_CONTROLLER:
                    hide();
                    break;
                case SHOW_BUFFER_PROGRESS:
                    updateBufferProgress();
                    break;
                case SHOW_PLAY_PROGRESS:
                    updatePlayProgress();
                    break;
                case REMOVE_CONTROLLER:
                    if (mAnchor != null) {
                        mAnchor.removeView(mRoot);
                        mIsAnimHiding = false;
                        mShowing = false;
                        LogUtil.i("zl", "MediaController hide mAnchor.removeView(mRoot)...");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public CustomerMediaController(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    }

    public CustomerMediaController(Context context) {
        super(context);
        mContext = context;
        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    }

    @Override
    public void onFinishInflate() {
        super.onFinishInflate();
        if (mRoot != null) {
            initControllerView(mRoot);
        }
    }

    @Override
    protected void setPlayerListeners() {
        // TODO Auto-generated method stub
        super.setPlayerListeners();

        updatePauseButton();
        if (mVideoView != null) {
            mVideoView.setOnSlideListener(new MySlideListener());
        }
    }

    /**
     * 设置MediaController 所依附的的父视图
     */
    @Override
    protected void setAnchorView(ViewGroup view) {
        // TODO Auto-generated method stub
        mAnchor = view;
        mRoot = getControllerView();
        setViewListeners();
        initControllerView(mRoot);
    }

    /**
     * 获取依附的父视图
     *
     * @return
     */
    public View getAnchorView() {
        return mAnchor;
    }

    /**
     * 默认控制器视图
     *
     * @return
     */
    protected View makeControllerView() {
        return LayoutInflater.from(mContext).inflate(R.layout.player_control_vod_fullscreen, this);
    }

    /**
     * 重新设置控制器视图
     *
     * @param view
     */
    public void setControllerView(View view) {
        if (mAnchor != null) {
            mAnchor.removeView(mRoot);
            mShowing = false;
            mIsAnimShowing = false;
            mIsAnimHiding = false;
        }
        mRoot = view;
    }

    /**
     * 设置快进快退手势视图
     *
     * @param view
     */
    public void setGestureView(View view) {
        this.mGestureView = view;

        initGestureView(mGestureView);
    }

    /**
     * 设置音量控制视图
     *
     * @param view
     */
    public void setVolumeView(View view) {
        this.mVolumeView = view;

        initVolumeView(mVolumeView);
    }

    private void initVolumeView(View rootView) {
        // TODO Auto-generated method stub
        mLlVerticalVolume = (LinearLayout) rootView.findViewById(R.id.ll_vetical_volume);
        mVsbVolume = (VerticalSeekBar) rootView.findViewById(R.id.vsb_volume);
        mVsbVolume.setMax(mMaxVolume);
        mVsbVolume.setProgress(mCurrentVolume);
    }

    private void initGestureView(View rootView) {
        // TODO Auto-generated method stub
        mRlRootGesture = (RelativeLayout) rootView.findViewById(R.id.rl_root_gesture);
        ivGestureDirection = (ImageView) rootView.findViewById(R.id.iv_gesture_direction);
        tvGestureCur = (TextView) rootView.findViewById(R.id.tv_current_time);
        tvGestureTotal = (TextView) rootView.findViewById(R.id.tv_total_time);
    }

    /**
     * 是否竖屏
     *
     * @return
     */
    public boolean isPortraitScreen() {
        int mCurrentOrientation = mContext.getResources().getConfiguration().orientation;
        return mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT;
    }

    private void initControllerView(View rootView) {

        mRlTop = (RelativeLayout) rootView.findViewById(R.id.rl_top);
        mLlBottom = (LinearLayout) rootView.findViewById(R.id.ll_bottom);
        mLlLeft = (LinearLayout) rootView.findViewById(R.id.ll_left);
        mLlRight = (LinearLayout) rootView.findViewById(R.id.ll_right);
        mLlPlayMode = (LinearLayout) rootView.findViewById(R.id.ll_play_mode);
        mLlTimeShiftAdjust = (LinearLayout) rootView.findViewById(R.id.ll_time_shift_layout); //粒度调整区域


        mPauseButton = (ImageButton) rootView.findViewById(R.id.ibtn_play_pause);
        if (mPauseButton != null) {
            mPauseButton.setOnClickListener(mPauseListener);
        }

        mScheduleProgress = (SeekBar) rootView.findViewById(R.id.sb_player_seekbar);
        if (mScheduleProgress != null) {
            if (mScheduleProgress instanceof SeekBar) {
                SeekBar seeker = (SeekBar) mScheduleProgress;
                seeker.setOnSeekBarChangeListener(mSeekListener);
                seeker.setThumbOffset(1);
            }
            mScheduleProgress.setMax(1000);
        }

        mEndTime = (TextView) rootView.findViewById(R.id.tv_total_time);
        mCurrentTime = (TextView) rootView.findViewById(R.id.tv_current_time);
        mFileName = (TextView) rootView.findViewById(R.id.tv_video_name);
        if (mFileName != null) {
            mFileName.setText(mTitle);
        }
    }


    private void setViewListeners() {
        // TODO Auto-generated method stub
        mPauseListener = new OnClickListener() {
            public void onClick(View v) {
                int id = v.getId();
                if (id == R.id.ibtn_play_pause) {
                    if (isAdPlaying) {
                        return;
                    }
                    doPauseResume();
                    isVideoPaused = isPaused;
                    if (mOnClickPauseListener != null) {
                        mOnClickPauseListener.onClickPause(isPaused);
                    }
                }
            }
        };
        mSeekListener = new OnSeekBarChangeListener() {
            public void onStartTrackingTouch(SeekBar bar) {

                show(mDefaultTimeout, false);
                mHandler.removeMessages(SHOW_PLAY_PROGRESS);
                mHandler.removeMessages(FADE_OUT_CONTROLLER);
            }

            public void onProgressChanged(SeekBar bar, int progress,
                                          boolean fromuser) {
                mProgress = progress;
                if (!fromuser || mPlayer == null) {
                    return;
                }

                newPosition = (mDuration * progress) / 1000;
                newPercent = mPlayer.getBufferPercentage();
                newTime = StringUtil.generateTime(newPosition);

                if (mCurrentTime != null) {
                    mCurrentTime.setText(newTime);
                }
            }

            public void onStopTrackingTouch(SeekBar bar) {

                if (mPlayer == null) {
                    return;
                }
                nowPosition = mPlayer.getCurrentPosition();
                mPlayer.seekTo(newPosition);
                if (mOnVideoPlayListener != null) {
                    mIsVideoPlay = false;
                    mPlayer.pause();
                    mOnVideoPlayListener.onVideoLoading();
                }
            }
        };
    }

    @Override
    public void setFileName(String name) {
        // TODO Auto-generated method stub
        mTitle = name;
        if (mFileName != null) {
            mFileName.setText(mTitle);
        }
    }

    @Override
    public boolean isShowing() {
        // TODO Auto-generated method stub
        return mShowing;
    }

    @Override
    public void show() {
        show(mDefaultTimeout);
    }

    @Override
    public void show(int timeout) {
        show(timeout, true);
    }

    /**
     * 显示控制器，并判断是否发送消息更新进度条
     *
     * @param timeout
     * @param isUpdateProgress
     */
    public void show(int timeout, boolean isUpdateProgress) {
        if (isAdPlaying) {//如果广告正在播放，不显示控制器
            return;
        }
        if (!mShowing && mAnchor != null) {

            if (mIsAnimShowing) {
                return;
            }

            ViewParent rootParent = mRoot.getParent();
            if (rootParent != null && rootParent instanceof ViewGroup) {
                LogUtil.i("zl", "MediaController show rootParent is not null...");
                ViewGroup rootParentView = (ViewGroup) rootParent;
                rootParentView.removeView(mRoot);
                return;
            }

            mIsAnimShowing = true;
            ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            mAnchor.addView(mRoot, tlp);

            if (mFileName != null) {
                mFileName.requestFocus();
            }

            if (mShownListener != null) {
                mShownListener.onShown();
            }

            Animation upInAni = AnimationUtils.loadAnimation(mContext, R.anim.base_push_up_in);
            Animation bottomInAni = AnimationUtils.loadAnimation(mContext, R.anim.base_push_down_in);
            Animation leftInAni = AnimationUtils.loadAnimation(mContext, R.anim.base_push_left_in);
//			Animation rightInAni = AnimationUtils.loadAnimation(mContext, R.anim.base_push_right_in);
            bottomInAni.setAnimationListener(new AnimationListener() {

                @Override
                public void onAnimationStart(Animation animation) {
                    // TODO Auto-generated method stub
                    mIsAnimShowing = true;
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    // TODO Auto-generated method stub
                    mIsAnimShowing = false;
                    mShowing = true;
                }
            });
            if (mRlTop != null && mRlTop.isShown()) {
                mRlTop.startAnimation(upInAni);
            }
            if (mLlBottom != null && mLlBottom.isShown()) {
                mLlBottom.startAnimation(bottomInAni);
            }
            if (mLlLeft != null && mLlLeft.isShown()) {
                mLlLeft.startAnimation(leftInAni);
            }
            /*if (mLlRight != null) {
				mLlRight.startAnimation(rightInAni);
			}*/
        }
        updatePauseButton();
        mHandler.removeMessages(FADE_OUT_VOLUME);
        mHandler.removeMessages(FADE_OUT_CONTROLLER);
        mHandler.sendEmptyMessageDelayed(FADE_OUT_CONTROLLER, timeout);
        if (isUpdateProgress && !isLiveFlag) {
            mHandler.sendEmptyMessage(SHOW_PLAY_PROGRESS);
            mHandler.sendEmptyMessage(SHOW_BUFFER_PROGRESS);
        }

        if (mProgress == 1000 && mOnVideoPlayListener != null) {
            mOnVideoPlayListener.onVideoPlayComplete();
        }

    }

    /**
     * 隐藏控制器，默认动画隐藏
     */
    public void hide() {
        hide(true);
    }

    /**
     * 隐藏控制器
     *
     * @param isAnimation 是否以动画的形式隐藏
     */
    public void hide(boolean isAnimation) {
        if (mAnchor == null) {
            return;
        }
        if (mShowing) {

            if (mIsAnimHiding) {
                return;
            }

            mHandler.removeMessages(FADE_OUT_CONTROLLER);
            mHandler.removeMessages(SHOW_PLAY_PROGRESS);
            mHandler.removeMessages(SHOW_BUFFER_PROGRESS);
            // mAnchor.removeView(mRoot);

            AnimController.getInstance().scaleOut(mLlPlayMode, 200, 0);//全屏码率窗口隐藏
            AnimController.getInstance().scaleOut(mLlVerticalVolume, 200, 0);//全屏音量窗口隐藏
            AnimController.getInstance().slideBottomOut(mLlTimeShiftAdjust, 350, 0);//全屏粒度按钮隐藏
            AnimController.getInstance().slideRightOut(mLlRight, 350, 0);//全屏右侧列表隐藏

            if (mHiddenListener != null) {
                mHiddenListener.onHidden();
            }

            if (!isAnimation && mAnchor != null) {
                mAnchor.removeView(mRoot);
                mShowing = false;
                return;
            }

            Animation upOutAni = AnimationUtils.loadAnimation(mContext, R.anim.base_push_up_out);
            Animation bottomOutAni = AnimationUtils.loadAnimation(mContext, R.anim.base_push_down_out);
            Animation leftOutAni = AnimationUtils.loadAnimation(mContext, R.anim.base_push_left_out);

            bottomOutAni.setAnimationListener(new AnimationListener() {

                @Override
                public void onAnimationStart(Animation animation) {
                    // TODO Auto-generated method stub
                    mIsAnimHiding = true;
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    // TODO Auto-generated method stub
//					mAnchor.removeView(mRoot);//直接在方法内调用该方法在部分手机(4.0.4系统)会报错，通过handler发送消息解决
                    mHandler.sendEmptyMessage(REMOVE_CONTROLLER);
                }
            });
            if (mRlTop != null && mRlTop.isShown()) {
                mRlTop.startAnimation(upOutAni);
            }
            if (mLlBottom != null && mLlBottom.isShown()) {
                mLlBottom.startAnimation(bottomOutAni);
            }
            if (mLlLeft != null && mLlLeft.isShown()) {
                mLlLeft.startAnimation(leftOutAni);
            }
        }
    }


    public interface OnShownListener {
        public void onShown();
    }

    public interface OnClickPauseListener {
        public void onClickPause(boolean isPaused);
    }

    public interface OnHiddenListener {
        public void onHidden();
    }

    public void setOnShownListener(OnShownListener l) {
        mShownListener = l;
    }

    public void setOnClickPauseListener(OnClickPauseListener mOnClickPauseListener) {
        this.mOnClickPauseListener = mOnClickPauseListener;
    }

    public void setOnHiddenListener(OnHiddenListener l) {
        mHiddenListener = l;
    }

    /**
     * 更新缓冲进度
     */
    private void updateBufferProgress() {
        if (mPlayer == null) {
            return;
        }
        //int percent = mPlayer.getBufferPercentage();
        int percent = mCurrentBufferPercentage;
        if (mScheduleProgress != null) {
            //System.out.println("percent = " + percent);
            mScheduleProgress.setSecondaryProgress(percent * 10);
        }
    }

    /**
     * getDuration拿到的播放时长不准确，重新设置，可以从服务器获取
     * 暂有问题，还需修改
     *
     * @param duration
     */
    public void setDuration(int duration) {
        this.mDuration = duration;
    }

    /**
     * 清除数据，重新初始化
     */
    public void clear() {
        newPosition = 0;
        nowPosition = 0;
        mDuration = 0;
        newPercent = 0;
        mProgress = 0;
//		isSeekToZero = false;
//        mIsFirstPlay = true;
        mIsVideoPlay = false;
        isPaused = false;
        isVideoPaused = false;
        LogUtil.i("zl", "Mediacontroller clear mIsVideoPlay = " + mIsVideoPlay);
		/*if(mScheduleProgress != null){
			mScheduleProgress.setProgress(0);
			mScheduleProgress.setSecondaryProgress(0);
		}*/
    }

    /**
     * 更新播放进度
     */
    private void updatePlayProgress() {
        if (mPlayer == null) {
            return;
        }
        long duration = mPlayer.getDuration();
        long position = mPlayer.getCurrentPosition();

        mDuration = duration;
//		LogUtil.i("zl","updatePlayProgress:position = " + position);
//		LogUtil.i("zl","updatePlayProgress:mDuration = " + mDuration);

//		if(!isSeekSuccess(position)){
//			return;
//		}

        if (mScheduleProgress != null) {
            if (mDuration > 0) {
                int pos = (int) (1000L * position / mDuration);
//				LogUtil.i("zl","updatePlayProgress:pos = " + pos);
                mScheduleProgress.setProgress(pos);
            }
        }
		
		/*if(position > mDuration && mOnVideoPlayListener != null){
			mOnVideoPlayListener.onVideoPlayComplete();
		}*/

        if (mCurrentTime != null) {
//			LogUtil.i("zl","updatePlayProgress:StringUtil.generateTime(position = " + StringUtil.generateTime(position));
            mCurrentTime.setText(StringUtil.generateTime(position > mDuration ? mDuration : position));
        }
        if (mEndTime != null) {
            mEndTime.setText(StringUtil.generateTime(mDuration));
        }

        if (mShowing || mIsAnimShowing) {
            updatePauseButton();
            mHandler.sendEmptyMessageDelayed(SHOW_PLAY_PROGRESS, 1000 - (position % 1000));
        }
    }


    /**
     * 设置系统音量
     *
     * @param index
     */
    public void setVolume(int index) {
        if (mLlVerticalVolume == null) {//如果竟是控制视图为空，不作操作
            return;
        }
        if (index < 0) {
            index = 0;
        } else if (index > mMaxVolume) {
            index = mMaxVolume;
        }
        if (mAudioManager != null) {
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, AudioManager.FLAG_SHOW_UI);
            if (mVsbVolume != null) {
                mVsbVolume.setProgress(index);
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int keyCode = event.getKeyCode();
        if (event.getRepeatCount() == 0
                && (keyCode == KeyEvent.KEYCODE_HEADSETHOOK
                || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keyCode == KeyEvent.KEYCODE_SPACE)) {
            doPauseResume();
            // show(sDefaultTimeout);
            if (mPauseButton != null)
                mPauseButton.requestFocus();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP) {
            if (mPlayer.isPlaying()) {
                mPlayer.pause();
                updatePauseButton();
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK
                || keyCode == KeyEvent.KEYCODE_MENU) {
            hide();
            return true;
        } else {
            show(mDefaultTimeout);
        }
        return super.dispatchKeyEvent(event);
    }

    private void updatePauseButton() {
        if (mRoot == null || mPauseButton == null || mPlayer == null) {
            return;
        }

        //解决播放器被遮住，重新播放时，暂停按钮为暂停状态的问题
        if (!isVideoPaused) {
            isPaused = false;
        }

        if (!isPaused/*mPlayer.isPlaying()*/) {
            mPauseButton.setImageResource(R.drawable.player_pause);
        } else {
            mPauseButton.setImageResource(R.drawable.player_play);
        }
    }

    /**
     * 提供给外部调用更新播放按钮，当视频暂停状态下被覆盖时， 恢复时仍然为暂停状态
     */
    public void updatePause() {
        if (mPlayer == null) {
            return;
        }
        if (isVideoPaused) {
            return;
        } else {
            doPauseResume();
        }
    }

    private void doPauseResume() {
        if (mPlayer == null) {
            return;
        }
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
            isPaused = true;
            mHandler.removeMessages(SHOW_PLAY_PROGRESS);
            show(mDefaultTimeout, false);
        } else {
            mPlayer.start();
            isPaused = false;
            show(mDefaultTimeout, true);
        }
        updatePauseButton();
    }

    public View getControllerView() {
        if (mRoot == null) {
            mRoot = makeControllerView();
        }
        return mRoot;
    }

    public void setLiveFlag(boolean isLiveFlag) {
        this.isLiveFlag = isLiveFlag;
    }

    /**
     * 播放一个视频只有一个MediaController,可通过此方法设置是否正在播放广告，播放广告的时不显示MediaController
     *
     * @param isPlaying
     */
    public void setAdPlaying(boolean isPlaying) {
        this.isAdPlaying = isPlaying;
    }

    public boolean isAdPlaying() {
        return isAdPlaying;
    }

    public void hideProgressBar() {
        if (mScheduleProgress != null)
            mScheduleProgress.setVisibility(View.INVISIBLE);
    }

    public void showProgressBar() {
        if (mScheduleProgress != null)
            mScheduleProgress.setVisibility(View.VISIBLE);
    }

    class MySlideListener implements IMediaPlayer.OnSlideListener {

        @Override
        public void onSlideStart(int direction) {
            // TODO Auto-generated method stub
            if (!mIsVideoPlay || mPlayer == null) {
                return;
            }
            switch (direction) {
                case IMediaPlayer.SLIDE_STATE_LEFT:
                case IMediaPlayer.SLIDE_STATE_RIGHT:
                    if (mGestureView == null || isLiveFlag) {
                        return;
                    }
                    if (mLlVerticalVolume != null) {
                        mLlVerticalVolume.setVisibility(View.GONE);//隐藏音量控制视图
                        mHandler.removeMessages(FADE_OUT_VOLUME);//取消发送隐藏音量控制视图消息
                    }
                    mRlRootGesture.setVisibility(View.VISIBLE);//显示手势视图
                    nowPosition = mPlayer.getCurrentPosition();
                    if (isShowing()) {
                        mHandler.removeMessages(SHOW_PLAY_PROGRESS);
                        mHandler.removeMessages(FADE_OUT_CONTROLLER);
                    }
                    break;
                case IMediaPlayer.SLIDE_STATE_UP:
                case IMediaPlayer.SLIDE_STATE_DOWN:
                    if (mLlVerticalVolume == null) {
                        return;
                    }
                    mLlVerticalVolume.setVisibility(View.VISIBLE);
                    mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    mVsbVolume.setProgress(mCurrentVolume);

                    mHandler.removeMessages(FADE_OUT_VOLUME);
                    if (isShowing()) {
                        mHandler.removeMessages(SHOW_PLAY_PROGRESS);
                        mHandler.removeMessages(FADE_OUT_CONTROLLER);
                    }

                    break;
                case IMediaPlayer.SLIDE_STATE_NONE:
                    break;
                default:
                    break;
            }

        }

        @Override
        public void onSlideEnd(int direction, int distance) {
            // TODO Auto-generated method stub
            if (!mIsVideoPlay || mPlayer == null) {
                return;
            }
            switch (direction) {
                case IMediaPlayer.SLIDE_STATE_LEFT:
                case IMediaPlayer.SLIDE_STATE_RIGHT:
                    if (mGestureView == null || isLiveFlag) {
                        return;
                    }
                    mRlRootGesture.setVisibility(View.GONE);

                    newPosition = nowPosition + distance * 1000;//横向滑动距离*1000转换成毫秒数
                    nowPosition = mPlayer.getCurrentPosition();//重新获取seekTo前的进度，去除拖动过程中扔在播放时的进度误差
                    if (mDuration == 0) {
                        return;
                    }
                    if (newPosition <= 0) {
                        newPosition = 0;
                    }
                    if (newPosition >= mDuration) {
                        newPosition = mDuration;
                    }
                    if (newPosition >= mDuration) {
                        newPosition = mDuration - 1000;//直接seek到最后一帧也有问题，往前1s
                    }

                    //以下处理同拖动进度条时处理方式一致
                    mPlayer.seekTo(newPosition);
                    if (mOnVideoPlayListener != null) {
                        mIsVideoPlay = false;
                        mPlayer.pause();
                        mOnVideoPlayListener.onVideoLoading();
                    }
                    break;
                case IMediaPlayer.SLIDE_STATE_UP:
                case IMediaPlayer.SLIDE_STATE_DOWN:
                    if (mLlVerticalVolume == null) {
                        return;
                    }
                    if (!isShowing()) {
                        mHandler.sendEmptyMessageDelayed(FADE_OUT_VOLUME, 2000);
                    } else {
                        show();
                    }
                    mCurrentVolume -= distance;
                    break;
                case IMediaPlayer.SLIDE_STATE_NONE:
                    mHandler.sendEmptyMessage(FADE_OUT_VOLUME);
                    if (mRlRootGesture != null) {
                        mRlRootGesture.setVisibility(View.GONE);
                    }
                    show();
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onSliding(int direction, int distance) {
            // TODO Auto-generated method stub
            if (!mIsVideoPlay || mPlayer == null) {
                return;
            }
            switch (direction) {
                case IMediaPlayer.SLIDE_STATE_RIGHT://distance 大于0
                    if (mGestureView == null || isLiveFlag) {
                        return;
                    }
                    ivGestureDirection.setBackgroundResource(R.drawable.player_next);//手势方向
                    tvGestureTotal.setText(StringUtil.generateTime(mDuration)); //手势视图总时间设置

                    long rigthToPosition = nowPosition + distance * 1000;//nowPosition在onSlideStart方法中获取，距离*1000转换成毫秒数
                    mDuration = mDuration == 0 ? mPlayer.getDuration() : mDuration;
                    if (rigthToPosition > mDuration) {
                        mCurrentTime.setText(StringUtil.generateTime(mDuration));//mediacontroller当前时间设置
                        tvGestureCur.setText(StringUtil.generateTime(mDuration)); //手势视图当前时间设置
                    } else {
                        mCurrentTime.setText(StringUtil.generateTime(rigthToPosition));
                        tvGestureCur.setText(StringUtil.generateTime(rigthToPosition));
                    }

                    if (mDuration > 0) {
                        int pos = (int) (1000L * rigthToPosition / mDuration);
                        mScheduleProgress.setProgress(pos);
                    }

                    break;
                case IMediaPlayer.SLIDE_STATE_LEFT://distance 小于0
                    if (mGestureView == null || isLiveFlag) {
                        return;
                    }
                    ivGestureDirection.setBackgroundResource(R.drawable.player_previous);
                    mDuration = mDuration == 0 ? mPlayer.getDuration() : mDuration;
                    tvGestureTotal.setText(StringUtil.generateTime(mDuration));

                    long leftToPosition = nowPosition + distance * 1000;//nowPosition在onSlideStart方法中获取，距离*1000转换成毫秒数
                    tvGestureCur.setText(StringUtil.generateTime(leftToPosition));
                    mCurrentTime.setText(StringUtil.generateTime(leftToPosition));

                    if (mDuration > 0 && leftToPosition >= 0) {
                        int pos = (int) (1000L * leftToPosition / mDuration);
                        mScheduleProgress.setProgress(pos);
                    }

                    break;
                case IMediaPlayer.SLIDE_STATE_UP://distance 小于0
                    setVolume(mCurrentVolume - distance);
                    break;
                case IMediaPlayer.SLIDE_STATE_DOWN://distance 大于0
                    setVolume(mCurrentVolume - distance);
                    break;
                case IMediaPlayer.SLIDE_STATE_NONE:
                    LogUtil.i(TAG, "SLIDE_STATE_NONE distance = " + distance);
                    break;

                default:
                    break;
            }
        }

    }

}
